import dayjs from 'dayjs'
import { Request } from 'express'
import { v4 as uuidv4 } from 'uuid'
import { setKey } from './redis'

/**
 * 判断是否为空
 * @param {*} param
 */
export function isEmpty(param: any) {
  return [undefined, null, ''].includes(param)
}

/**
 * 拉入黑名单
 * @param {Request} req
 */
export async function blockUser(req: Request) {
  const token = req.headers.authorization?.replace('Bearer ', '')
  const expiresTimestamp = req.expiresTimestamp as number
  const seconds = dayjs(expiresTimestamp * 1000).diff(dayjs(), 'second')
  await setKey(`token:${req.userId}:${token}`, 1, seconds)
}

/**
 * 对象key值排序
 * @param {object} obj
 */
export function objKeySort(obj: Record<string, any>) {
  const newKey = Object.keys(obj).sort()
  const newObj = {} as Record<string, any>
  for (const i of newKey) {
    newObj[i] = obj[i]
  }
  return newObj
}

/**
 * 生成订单号
 * @param {boolean} isUuid 是否生成uuid 默认false 年月日时分秒+随机数
 */
export function generateTradeNo(isUuid: boolean = false) {
  if (isUuid) {
    return uuidv4().replace(/-/g, '')
  }
  const formattedDate = dayjs().format('YYYYMMDDHHmmss')
  const randomNum = Math.floor(Math.random() * 900) + 100
  return formattedDate + randomNum
}
